/**
 * 
 */
package com.airnewslinkosky.ticket.ui.order;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.FlightOrder;
import com.airnewslinkosky.ticket.model.OrderInfo;
import com.airnewslinkosky.ticket.model.OrderInfoResult;
import com.airnewslinkosky.ticket.model.TotalOrderInfoResult;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.flight.CreditCard;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

/**
 * @author luoxz
 *
 */
public class OrderDetailOutTicket extends BaseActivity implements OnClickListener {
	
	public final static int SUCCESS = 0;
	public final static int FAIL = 1;
	public final static int CANCEL_SUCCESS = 2;
	
	public static OrderInfo ORDER_INFO;
	public static FlightOrder ORDER_DETAIL;
	
	private ProgressDialog progressDialog = null;
	
	Button buttonPay, buttonCancel;
	
	TextView departureDate, departureWeek, flightNo,
	order_status, order_no, order_date,totalAmount,
	ticketOrderNo,passengerName,course,
	ticketOrder_date,tripType,rebate,ticket_status,
	
	fromCity, flight_depart, fromtime, fromaf, 
	toCity, flight_arrive, totime, toaf, 
	airc, baseCabin, food, stopNo, flight_price_title2, cabinPrice, discount, price, basePrice, fuelTax,
	airc0, others, airc1, airc2,
	
	consigneeName,consigneePhone,consigneeAddress,itineraryNo,
	passenger_name, passenger_id_number,
	contactor_name, contactor_mobile,
	sumPrice;
	private LinearLayout itinerary_info_sum_layout;
	
	private AddrUtil addrUtil;
	
	private FlyUtil flyUtil;
	
	//后退回列表页时使用
	public static List<OrderInfo> orderist = new ArrayList<OrderInfo> ();
	private Toast toast;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.order_detail_out_ticket);
		activityList.add(this);
		
		//初始化接钮
		findViewById(R.id.btn_pay).setOnClickListener(this);
		findViewById(R.id.btn_cancel).setOnClickListener(this);
		findViewById(R.id.backBut).setOnClickListener(this);
		
		//初始化地址参数
		addrUtil = new AddrUtil(this);
		//初始化航空参数
		flyUtil = new FlyUtil(this);

		//初始化字段
//		departureDate = (TextView) findViewById(R.id.departureDate);
//		departureWeek = (TextView) findViewById(R.id.departureWeek);
//		flightNo = (TextView) findViewById(R.id.flightNo); 
		//总订单信息
		order_status = (TextView) findViewById(R.id.order_status);
		order_no = (TextView) findViewById(R.id.order_no);
		order_date = (TextView) findViewById(R.id.order_date);
		totalAmount =  (TextView) findViewById(R.id.totalAmount);
		
		
		passengerName =  (TextView) findViewById(R.id.passengerName); 
		ticketOrderNo =  (TextView) findViewById(R.id.ticketOrderNo); 
		course =  (TextView) findViewById(R.id.course); 
		ticketOrder_date =  (TextView) findViewById(R.id.ticketOrder_date); 
		tripType =  (TextView) findViewById(R.id.tripType); 
		rebate =  (TextView) findViewById(R.id.rebate); 
		ticket_status =  (TextView) findViewById(R.id.ticket_status); 
		
		fromCity = (TextView) findViewById(R.id.fromCity); 
		flight_depart = (TextView) findViewById(R.id.flight_depart); 
		fromtime = (TextView) findViewById(R.id.fromtime);  
		fromaf = (TextView) findViewById(R.id.fromaf);  
		toCity = (TextView) findViewById(R.id.toCity);
		flight_arrive = (TextView) findViewById(R.id.flight_arrive);
		totime = (TextView) findViewById(R.id.totime);
		toaf = (TextView) findViewById(R.id.toaf);
		airc = (TextView) findViewById(R.id.airc);
		baseCabin = (TextView) findViewById(R.id.baseCabin);
		food = (TextView) findViewById(R.id.food);
		stopNo = (TextView) findViewById(R.id.stopNo);
		flight_price_title2 = (TextView) findViewById(R.id.flight_price_title2);
		cabinPrice = (TextView) findViewById(R.id.cabinPrice);
		discount = (TextView) findViewById(R.id.discount);
		price = (TextView) findViewById(R.id.price);
		basePrice = (TextView) findViewById(R.id.basePrice);
		fuelTax = (TextView) findViewById(R.id.fuelTax);
		airc0 = (TextView) findViewById(R.id.airc0);
		others = (TextView) findViewById(R.id.others);
		airc1 = (TextView) findViewById(R.id.airc1);
		airc2 = (TextView) findViewById(R.id.airc2);
		
		itinerary_info_sum_layout = (LinearLayout) findViewById(R.id.itinerary_info_sum_layout);
		
		consigneeName = (TextView) findViewById(R.id.consigneeName);
		consigneePhone = (TextView) findViewById(R.id.consigneePhone);
		consigneeAddress = (TextView) findViewById(R.id.consigneeAddress);
		itineraryNo = (TextView) findViewById(R.id.itineraryNo);
		
		passenger_name = (TextView) findViewById(R.id.passenger_name);
		passenger_id_number = (TextView) findViewById(R.id.passenger_id_number);
		contactor_name = (TextView) findViewById(R.id.contactor_name);
		contactor_mobile = (TextView) findViewById(R.id.contactor_mobile);
		sumPrice = (TextView) findViewById(R.id.sumPrice);
		
		renderData();
	}
	
	//初始化数据
	private void renderData() {
		//TODO： 再次查找数据
		
		String departureDateValue = "";
		String departureCityValue = "";
		String departureTimeValue = "";
		String arrivalCityValue = "";
		String airLine = "";
		
		
		if(ORDER_DETAIL.FlightID!=null){
			String[] result = ORDER_DETAIL.FlightID.split(" ");
			airLine = result[2];
			departureCityValue = addrUtil.getCityByCode(result[0]) != null ? addrUtil.getCityByCode(result[0]).getAirName() : "未知城市";
			arrivalCityValue = addrUtil.getCityByCode(result[1]) != null ? addrUtil.getCityByCode(result[1]).getAirName() : "未知城市";
			departureDateValue = result[3];
		}
		
		
		order_status.setText(flyUtil.orderStatusMap.get(ORDER_INFO.Status));
		order_no.setText(ORDER_INFO.OrderNo);
		order_date.setText(ORDER_INFO.CreateTime);
		
		
		passengerName.setText(ORDER_DETAIL.PassengerName);
		ticketOrderNo.setText(ORDER_DETAIL.TicketOrderNo);
		if(ORDER_DETAIL.Course!=null){
			String[] result = ORDER_DETAIL.Course.split(" ");
			airLine = result[2];
			departureCityValue = addrUtil.getCityByCode(result[0]) != null ? addrUtil.getCityByCode(result[0]).getAirName() : "未知城市";
			arrivalCityValue = addrUtil.getCityByCode(result[1]) != null ? addrUtil.getCityByCode(result[1]).getAirName() : "未知城市";
			departureDateValue = result[3];
			course.setText(flyUtil.getName(airLine.substring(0, 2)) + "  " + departureCityValue + "->" + arrivalCityValue);
			ticketOrder_date.setText(departureDateValue);
			airc.setText(airLine);
		}
		
		ticket_status.setText(flyUtil.orderStatusMap.get(ORDER_INFO.Status));//这一块可能要修改
		tripType.setText(flyUtil.getTripTypeCode(Integer.valueOf(ORDER_DETAIL.TripType)));
		baseCabin.setText(ORDER_DETAIL.Cabin + " " +  flyUtil.getJClassName(ORDER_DETAIL.Cabin));
		
		
		flight_price_title2.setText("");
		
		cabinPrice.setText("￥" +ORDER_DETAIL.CabinPrice);
		cabinPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
		
		price.setText("￥" + String.valueOf(Float.valueOf(ORDER_DETAIL.CabinPrice) - Float.valueOf(ORDER_DETAIL.Rebate)));
		
		rebate.setText("返利￥ " + ORDER_DETAIL.Rebate);
		
		String airportTaxV = (ORDER_DETAIL.AirportTax.equals("") ||  (ORDER_DETAIL.AirportTax == null) ? "0" : ORDER_DETAIL.AirportTax) ;
		String fuelTaxV = (ORDER_DETAIL.FuelTax.equals("") || (ORDER_DETAIL.FuelTax == null) ? "0" : ORDER_DETAIL.FuelTax);
		fuelTax.setText("￥" + airportTaxV + "/￥" + fuelTaxV);
		
//		airc0.setText("同等舱位免费更改。");
//		others.setText("需收取票面价5%的退票费,退票费低于50元按50元收取。");
//		airc1.setText("不得签转。");
		
		passenger_name.setText(ORDER_DETAIL.PassengerName + "  " + flyUtil.getPassengerTypeCode(Integer.valueOf(ORDER_DETAIL.PassengerType)));
		passenger_id_number.setText(flyUtil.getCardTypeLabel(ORDER_DETAIL.PassengerIDType) + "  " + ORDER_DETAIL.PassengerIDNo);
		
		contactor_name.setText(ORDER_DETAIL.ContactName);
		contactor_mobile.setText(ORDER_DETAIL.ContactPhone);
		
		System.out.println("ORDER_DETAIL.ItineraryInfo.getItineraryOrderNo()="+ORDER_DETAIL.ItineraryInfo.getItineraryOrderNo());
		if(ORDER_DETAIL.ItineraryInfo.getItineraryOrderNo().equals("")){
			itinerary_info_sum_layout.setVisibility(View.GONE);
		} else {
			consigneeName.setText(ORDER_DETAIL.ItineraryInfo.getConsigneeName());
			consigneePhone.setText(ORDER_DETAIL.ItineraryInfo.getConsigneePhone());
			consigneeAddress.setText(ORDER_DETAIL.ItineraryInfo.getConsigneeAddress());
			itineraryNo.setText(ORDER_DETAIL.ItineraryInfo.getItineraryOrderNo());
		}
		
		float sumPriceV = Float.valueOf(ORDER_DETAIL.CabinPrice) - Float.valueOf(ORDER_DETAIL.Rebate) + Float.valueOf(airportTaxV) + Float.valueOf(fuelTaxV);
		
		sumPrice.setText("￥" + String.valueOf(sumPriceV));
		totalAmount.setText("￥" + String.valueOf(sumPriceV));

		//根据状态显示可操作的按键
		String flyOrderStatus = ORDER_INFO.Status;//ORDER_DETAIL.Status;TODO要修改
		if ("0".equalsIgnoreCase(flyOrderStatus)) {
			findViewById(R.id.btn_pay).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
		} else if ("1".equalsIgnoreCase(flyOrderStatus)) {
			findViewById(R.id.btn_refundment).setVisibility(View.VISIBLE);
		} else if ("2".equalsIgnoreCase(flyOrderStatus)) {
			findViewById(R.id.btn_bounce_ticket).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_abolish_ticket).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_change_date).setVisibility(View.VISIBLE);
		}
		
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_pay: {
			//付款
			String[] FlightOrderNOArray = new String[ORDER_INFO.TicketOrders.size()];
			for (int i = 0; i < FlightOrderNOArray.length; i ++) {
				FlightOrderNOArray[i] = ORDER_INFO.TicketOrders.get(i).OrderNo;
			}
			
			TotalOrderInfoResult orderResult = new TotalOrderInfoResult();
			orderResult.OrderNO = ORDER_INFO.OrderNo;
			orderResult.FlightOrderNO = FlightOrderNOArray;
			
			//跳转到信用卡支付页面
			Intent intent = new Intent();
			intent.setClass(OrderDetailOutTicket.this, CreditCard.class);
			CreditCard.totalOrderInfoResult = orderResult;
			CreditCard.sumPriceFormat = ORDER_INFO.TotalAmount;
			startActivity(intent);
			break;
		}
		case R.id.btn_cancel: {
			//申请退票
			Log.i("OrderDetail", "btn_cancel");
			progressDialog = ProgressDialog.show(this, "请稍等...", "申请退票中...",true);
			final Thread thread1 = new Thread() {
				public void run() {
					OrderInfoResult orderResult = WebAccessor.applyForRefund(OrderDetailOutTicket.this, ORDER_DETAIL.TicketOrderNo,"","","","");
					if (progressDialog.isShowing()) {
						if (progressDialog.isShowing()) {
							if (orderResult== null) {
								Message msg = new Message();
								msg.what = FAIL;
								msg.obj = "申请退票操作失败";
								myHandler.sendMessage(msg);
							}else if(!"0".equals(orderResult.Ret_Code)){
								Message msg = new Message();
								msg.what = FAIL;
								msg.obj = orderResult.Ret_Msg;
								myHandler.sendMessage(msg);
							}else{
								Message msg = new Message();
								msg.what = CANCEL_SUCCESS;
								myHandler.sendMessage(msg);
							}
							progressDialog.dismiss();
						}
					}
				}
			};
			progressDialog.setCancelable(true);
			thread1.start();
			break;
		}
		case R.id.backBut: {
			Intent intent = new Intent(OrderDetailOutTicket.this, OrderList.class);
			OrderList.UPDATE_INDICATOR = true;
			startActivity(intent);
		}
		}
		
	}

	//处理
	Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				toast = Toast.makeText(OrderDetailOutTicket.this, "操作成功", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case FAIL:
				toast = Toast.makeText(OrderDetailOutTicket.this, (String)msg.obj, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case CANCEL_SUCCESS:
				toast = Toast.makeText(OrderDetailOutTicket.this, "申请退票成功", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				//更新页面状态
//				order_status.setText(FlyUtil.orderStatusMap.get("11"));
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
